import re
import random
import time,datetime
import uuid
import socket
from hashlib import md5,sha1


class FunctionHelper():

    @staticmethod
    def __replace_func(matched):
        value = matched.group('value')
        func = re.search('\\$(.*?)\\$', value).group(1)
        return_value = getattr(Function, func)()

        return str(return_value)

    @staticmethod
    def parse_function_str(function_str):
        return re.sub('(?P<value>\\$(.*?)\\$)', FunctionHelper.__replace_func, function_str)


class Function():

    @staticmethod
    def random_string(randomlength=16):
        """
        生成一个指定长度的随机字符串
        """
        random_str = ''
        base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
        length = len(base_str) - 1
        for i in range(randomlength):
            random_str += base_str[random.randint(0, length)]
        return random_str

    @staticmethod
    def MD5(string):
        """
        将字符串使用MD5算法加密
        """
        return md5(str(string).encode('utf8')).hexdigest()

    @staticmethod
    def SHA1(string):
        """
        将字符串使用SHA1算法加密
        """
        return sha1(str(string).encode('utf-8')).hexdigest()

    @staticmethod
    def times(fmt=None):

        """
          生成时间戳
        """
        if fmt == None:

            t = time.time()
            return int(round(t * 1000))
        else:

            return datetime.datetime.now().strftime(fmt)

    @staticmethod
    def UUID():
        """
            生成UUID
        """
        return uuid.uuid4()

    @staticmethod
    def machine_ip():

        '''
            获取本机IP
        '''
        name = socket.getfqdn(socket.gethostname())
        address = socket.gethostbyname(name)
        return address
